<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="24" :lg="8">
        <el-card class="profile-card profile-info-card">
          <div class="profile-avatar-container">
            <el-avatar 
              :size="120" 
              :src="form.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" 
              class="profile-avatar"
            />
            <div v-if="isEditing" class="avatar-edit">
              <el-input v-model="form.avatar" placeholder="请输入头像URL" class="avatar-url-input" />
              <el-button size="small" type="primary" class="change-avatar-btn" @click="updateAvatar">更新头像</el-button>
            </div>
          </div>
          
          <div class="profile-header">
            <h2 class="profile-name">{{ form.username || '用户' }}</h2>
            <div class="profile-id">ID: {{ form.userId }}</div>
          </div>
          
          <div class="profile-roles">
            <h3 class="section-title">我的角色</h3>
            <div class="roles-list">
              <el-tag 
                v-for="role in userInfo.roles" 
                :key="role"
                class="role-tag"
                :type="getTagType(role)"
                effect="light"
              >
                {{ getRoleName(role) }}
              </el-tag>
            </div>
          </div>
          
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleEdit"
            class="edit-btn"
          >
            {{ isEditing ? '保存' : '编辑资料' }}
          </el-button>
        </el-card>
      </el-col>
      
      <el-col :span="24" :lg="16">
        <el-card v-if="loading" class="profile-card loading-card">
          <el-skeleton :rows="6" animated />
        </el-card>
        
        <el-card v-else class="profile-card">
          <template #header>
            <div class="card-header">
              <h3>个人资料</h3>
            </div>
          </template>
          
          <el-form 
            ref="formRef"
            :model="form" 
            label-width="100px"
            :disabled="!isEditing"
            class="profile-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名">
                  <el-input v-model="form.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱">
                  <el-input v-model="form.email" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="昵称">
                  <el-input v-model="form.nickName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-select v-model="form.gender" placeholder="请选择">
                    <el-option :value="1" label="男" />
                    <el-option :value="2" label="女" />
                    <el-option :value="0" label="保密" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="地址">
              <el-input v-model="form.address" />
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 权限调试信息卡片 -->
        <el-card class="profile-card permission-card">
          <template #header>
            <div class="card-header">
              <h3>应用权限状态</h3>
            </div>
          </template>
          
          <el-table :data="appPermissions" stripe style="width: 100%">
            <el-table-column prop="title" label="应用名称" min-width="120" />
            <el-table-column prop="path" label="路径" min-width="100" />
            <el-table-column prop="requiredRoles" label="所需角色" min-width="150">
              <template #default="scope">
                {{ formatRequiredRoles(scope.row.requiredRolesArray) }}
              </template>
            </el-table-column>
            <el-table-column prop="hasPermission" label="访问权限" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.hasPermission ? 'success' : 'danger'">
                  {{ scope.row.hasPermission ? '有权访问' : '无权访问' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useUserProfile } from '../composables/useUserProfile'
import { ElMessage } from 'element-plus'
import { microApps } from '../microApps.config'
import { usePermissionStore } from '../store/permission'
import { useRoleStore } from '../store/role'
import { useUserStore } from '../store/user'
import { getUserProfile, updateUserProfile, updateUserAvatar } from '../api/user'

// 定义Profile接口
interface Profile {
  id?: number;
  nickName?: string;
  gender?: number;
  avatar?: string;
  address?: string;
  email?: string;
  userId?: number;
}

// 使用composable获取用户信息相关逻辑
const { 
  userInfo, 
  loading, 
  error, 
  fetchUserProfile
} = useUserProfile()

const userStore = useUserStore()
const permissionStore = usePermissionStore()
const roleStore = useRoleStore()

// 用户角色对象
const userRoleObjects = computed(() => userInfo.value.roleObjects || [])

// 应用权限列表
const appPermissions = computed(() => {
  return microApps.map(app => ({
    title: app.title,
    path: app.activeRule,
    requiredRoles: app.requiredRoles?.join(', ') || '无限制',
    requiredRolesArray: app.requiredRoles || [],
    hasPermission: checkAppPermission(app)
  }))
})

// 表单引用
const formRef = ref()

// 编辑状态
const isEditing = ref(false)

// 表单数据，响应式复制用户信息
const form = reactive({
  userId: '',
  username: '',
  avatar: '',
  nickName: '',
  gender: 0,
  email: '',
  address: ''
})

// 获取角色名称
const getRoleName = (roleCode: string): string => {
  const roleObj = userRoleObjects.value.find(r => r.code === roleCode)
  return roleObj?.name || roleStore.getRoleName(roleCode) || roleCode
}

// 格式化所需角色，显示名称而非代码
const formatRequiredRoles = (roles: string[]): string => {
  if (!roles?.length) return '无限制'
  return roles.map(role => getRoleName(role)).join(', ')
}

// 根据角色获取标签类型
const getTagType = (role: string): string => {
  const roleTypes: Record<string, string> = {
    'SUPER_ADMIN': 'danger',
    'ADMIN': 'warning',
    'TEACHER': 'success',
    'USER': 'info'
  }
  return roleTypes[role] || 'primary'
}

// 检查应用权限 - 修复超级管理员权限问题
const checkAppPermission = (app: any) => {
  const userRoles = userInfo.value.roles || []
  
  // 超级管理员始终有权限
  if (userRoles.includes('SUPER_ADMIN')) return true
  
  // 无角色要求或用户有任一所需角色
  const hasRequiredRole = !app.requiredRoles?.length || 
    app.requiredRoles.some((role: string) => userRoles.includes(role))
    
  // 无权限码要求或用户有权限
  const hasPermission = !app.permission || 
    permissionStore.hasPermission(app.permission)
    
  return hasRequiredRole && hasPermission
}

// 监听用户信息变化，更新表单
const updateForm = async () => {
  const profile = userInfo.value
  form.userId = profile.userId || ''
  form.username = profile.username || ''
  
  try {
    // 从API获取完整的用户资料
    if (profile.userId) {
      const response = await getUserProfile(Number(profile.userId))
      if (response.code === 200 && response.data) {
        const userData = response.data
        // 从profile中获取数据
        if (userData.profile) {
          form.avatar = userData.profile.avatar || ''
          form.nickName = userData.profile.nickName || ''
          form.gender = userData.profile.gender || 0
          form.email = userData.profile.email || ''
          form.address = userData.profile.address || ''
        }
      }
    }
  } catch (err) {
    console.error('获取用户资料失败:', err)
    // 使用默认值
    form.avatar = profile.avatar || ''
    form.email = profile.email || ''
  }
}

// 单独更新头像
const updateAvatar = async () => {
  if (!form.userId) return
  
  try {
    await updateUserAvatar(Number(form.userId), form.avatar)
    ElMessage.success('头像更新成功')
    
    // 更新Pinia存储的用户信息
    const updatedUserInfo = { ...userStore.userInfo, avatar: form.avatar }
    userStore.setUserInfo(updatedUserInfo)
    
    await fetchUserProfile() // 重新获取用户信息
    await updateForm() // 更新表单数据
  } catch (err) {
    console.error('更新头像失败:', err)
    ElMessage.error('更新头像失败')
  }
}

// 处理编辑/保存
const handleEdit = async () => {
  if (isEditing.value) {
    try {
      // 构建符合后端Profile实体的数据结构
      const profileData: Profile = {
        nickName: form.nickName,
        gender: form.gender,
        email: form.email,
        address: form.address,
        avatar: form.avatar
      }
      
      // 保存用户资料
      await updateUserProfile(Number(form.userId), profileData)
      
      // 更新Pinia存储的用户信息
      const updatedUserInfo = { 
        ...userStore.userInfo,
        avatar: form.avatar,
        email: form.email,
        // 可以添加其他需要更新的字段
      }
      userStore.setUserInfo(updatedUserInfo)
      
      ElMessage.success('个人信息更新成功')
      isEditing.value = false
      
      // 重新获取用户信息
      await fetchUserProfile()
      await updateForm() // 更新表单数据
    } catch (err) {
      console.error('更新个人信息失败:', err)
      ElMessage.error('更新个人信息失败')
    }
  } else {
    // 进入编辑模式
    isEditing.value = true
  }
}

// 组件挂载时加载用户信息
onMounted(async () => {
  try {
    await fetchUserProfile()
    await updateForm()
  } catch (err) {
    ElMessage.error('加载用户信息失败')
  }
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: var(--el-box-shadow-light);
  transition: all 0.3s ease;
}

.profile-card:hover {
  box-shadow: var(--el-box-shadow);
}

.profile-info-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 20px;
  text-align: center;
}

.profile-avatar-container {
  margin-bottom: 20px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-avatar {
  border: 4px solid var(--el-color-primary-light-8);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-edit {
  margin-top: 16px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.avatar-url-input {
  width: 100%;
}

.change-avatar-btn {
  width: 100%;
}

.profile-header {
  margin-bottom: 20px;
}

.profile-name {
  margin: 10px 0 5px;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.profile-id {
  color: var(--el-text-color-secondary);
  font-size: 0.9rem;
}

.section-title {
  margin: 15px 0 10px;
  font-size: 1.1rem;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.roles-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
  margin-bottom: 20px;
}

.role-tag {
  margin-bottom: 8px;
}

.edit-btn {
  width: 100%;
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.profile-form {
  padding: 10px;
}

.loading-card {
  padding: 40px 20px;
}

.permission-card {
  margin-top: 20px;
}

@media (max-width: 991px) {
  .profile-info-card {
    margin-bottom: 20px;
  }
}
</style> 